﻿using System.Collections.Generic;
using Game.Plugin.Parse;
using System.Linq;

namespace Game.Plugin
{
    public class PluginManager : IParser 
    {
        readonly static PluginManager _Instance = new PluginManager();

        public static PluginManager Instance
        {
            get { return _Instance; }
        }

        readonly IGamePlugin _RootPlugin = new RootPluginX();

        public IGamePlugin RootPlugin
        {
            get { return _RootPlugin; }
        }

        public bool CanParse(string token)
        {
            return _RootPlugin.CanParse(token);
        }

        public ICodeObject Parse(
            string token, 
            ParserContext context)
        {
            var parser = _RootPlugin.Find(token);
            if (parser != null)
            {
                return parser.Parse(token, context);
            }

            return new ErrorObject();
        }

        class RootPluginX : AbstractPlugin
        {
            public RootPluginX() : base(null, "/") {}

            public override ICodeObject Parse(
                string token,
                ParserContext context)
            {
                IExpression e = new RootExpression();
                context.Stack.Push(e);
                return e;
            }

        }

        class RootExpression : IExpression
        {
            public object Interpret(
                Dictionary<string, ICodeObject> variables)
            {
                return Instance.RootPlugin.Children.Aggregate("", (current, e) => current + (e.Name + " "));
            }
        }
    }

}
